package org.xiaojl.xcloud.tools.gateway.filter.pre;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.xiaojl.xcloud.tools.gateway.RpcResult;
import org.xiaojl.xcloud.tools.gateway.config.IpWhiteBlackProperties;
import org.xiaojl.xcloud.tools.gateway.kit.FilterKit;
import org.xiaojl.xcloud.tools.gateway.kit.IpKit;
import org.xiaojl.xcloud.tools.gateway.kit.JsonKit;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**  
 * <p>Title: IPWhiteBlackListFilter</p>  
 *
 * <p>Description: IP黑白名单过滤器</p>  
 *
 * @author jilong.xiao  
 * @date 2018年4月23日  
 */
@Component
public class IPWhiteBlackListFilter extends ZuulFilter {
	private static final Logger log = LoggerFactory.getLogger(IPWhiteBlackListFilter.class);
	@Autowired
	private IpWhiteBlackProperties ipwbProperties;
	
	@Override
	public boolean shouldFilter() {
		return FilterKit.isFilterFlag(RequestContext.getCurrentContext());
	}

	@Override
	public Object run() {
		RequestContext context = RequestContext.getCurrentContext();
		HttpServletRequest request = context.getRequest();
		String requestIp = IpKit.getRequestIp(request);
		if(log.isDebugEnabled()){
			log.debug(String.format("当前请求客户端IP：%s",requestIp));
		}
		
		//过滤白名单
		if(isWhiteIp(requestIp)){
			// 设值，让下一个Filter看到上一个Filter的状态  
			FilterKit.setFilterFlag(context,true);
			return null;
		}
		
		if(isBlackIp(requestIp)){
			RpcResult result = RpcResult.fail("非法IP", "", null);
			FilterKit.setFilterFlag(context,false);
			context.setSendZuulResponse(false);
			context.setResponseStatusCode(402);
			FilterKit.setRespBody(context, JsonKit.toJson(result));
			return null;
		}
		
		// 设值，让下一个Filter看到上一个Filter的状态  
		FilterKit.setFilterFlag(context,true);
		return null;
		
	}

	/**  
	 * <p>Title: isBlackIp</p>  
	 * <p>Description: 判断：是否在黑名单中</p>  
	 * @param requestIp
	 * @return  
	 */ 
	private boolean isBlackIp(String requestIp) {
		List<String> list = ipwbProperties.getBlist();
//		list = null;
//		list.size();
		if(log.isDebugEnabled()){
			log.debug(String.format("配置的黑名单IP：%s",list));  
		}
		if(list!=null && list.contains(requestIp)){
			return true;
		}
		return false;
	}

	/**  
	 * <p>Title: isWhiteIp</p>  
	 * <p>Description: 判断：是否在白名单中</p>  
	 * @param requestIp
	 * @return  
	 */ 
	private boolean isWhiteIp(String requestIp) {
		List<String> list = ipwbProperties.getWlist();
		if(log.isDebugEnabled()){
			log.debug(String.format("配置的白名单IP：%s",list));  
		}
		if(list!=null && list.contains(requestIp)){
			return true;
		}
		return false;
	}

	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return 5;
	}

}
